<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<svg class="logo-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
				校园运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="flex items-center gap-6">
				<div class="flex items-center gap-2">
					<img id="img-head" src="img/jstu1.webp" alt="用户头像">
					<span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
				</div>
				<div class="flex items-center gap-2">
					<a href="javascript:void(0)" class="denglu" @click="handleLogout">
						<svg class="logout-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
							<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
							<polyline points="16 17 21 12 16 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
							<line x1="21" y1="12" x2="9" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
						</svg>
						退出登录
					</a>
				</div>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }">
				<svg class="menu-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<rect x="3" y="3" width="7" height="7" stroke="currentColor" stroke-width="2"/>
					<rect x="14" y="3" width="7" height="7" stroke="currentColor" stroke-width="2"/>
					<rect x="14" y="14" width="7" height="7" stroke="currentColor" stroke-width="2"/>
					<rect x="3" y="14" width="7" height="7" stroke="currentColor" stroke-width="2"/>
				</svg>
				<a @click="$router.push('/admin')">系统管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
				<svg class="menu-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
					<circle cx="9" cy="7" r="4"></circle>
					<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
					<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
				</svg>
				<a @click="$router.push('/admin/users')">用户管理</a>
			</div>
			<div class="menu-item active">
				<svg class="menu-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
				操作日志
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/system-config' }">
				<svg class="menu-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<circle cx="12" cy="12" r="3"></circle>
					<path d="M12 1v6m0 6v6m4.22-13.22l4.24 4.24M1.54 9.54l4.24 4.24M1.54 14.46l4.24-4.24M18.46 14.46l4.24-4.24" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
				<a @click="$router.push('/admin/system-config')">系统配置</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/backup' }">
				<svg class="menu-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<polyline points="7 10 12 15 17 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
				<a @click="$router.push('/admin/backup')">数据备份</a>
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<div class="main-content-header">
				<h1>操作日志统计分析</h1>
				<div class="header-actions">
					<el-button @click="$router.push('/admin/operation-logs')">
						<svg class="btn-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
							<path d="M21 11H5M21 11l-7-7M21 11l-7 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
						</svg>
						返回日志列表
					</el-button>
				</div>
			</div>

			<!-- 时间范围选择 -->
			<div class="time-range-selector">
				<el-card shadow="never">
					<div class="time-range-content">
						<span class="time-label">统计时间范围：</span>
						<el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
							<el-radio-button label="today">今日</el-radio-button>
							<el-radio-button label="yesterday">昨日</el-radio-button>
							<el-radio-button label="week">本周</el-radio-button>
							<el-radio-button label="month">本月</el-radio-button>
							<el-radio-button label="year">本年</el-radio-button>
						</el-radio-group>
						<el-date-picker
							v-model="customDateRange"
							type="datetimerange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm:ss"
							value-format="YYYY-MM-DD HH:mm:ss"
							@change="handleCustomDateChange">
						</el-date-picker>
					</div>
				</el-card>
			</div>

			<!-- 统计概览卡片 -->
			<div class="overview-cards">
				<el-row :gutter="20">
					<el-col :span="6">
						<el-card shadow="hover" class="overview-card">
							<div class="overview-content">
								<div class="overview-icon primary">
									<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										<polyline points="14 2 14 8 20 8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										<line x1="16" y1="13" x2="8" y2="13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										<line x1="16" y1="17" x2="8" y2="17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
									</svg>
								</div>
								<div class="overview-info">
									<div class="overview-value">{{ statistics.totalLogs || 0 }}</div>
									<div class="overview-label">总操作次数</div>
									<div class="overview-trend" :class="{ positive: statistics.logsTrend > 0, negative: statistics.logsTrend < 0 }">
										<svg v-if="statistics.logsTrend > 0" class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 6 13.5 15.5 8.5 10.5 1 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 6 23 6 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										<svg v-else class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 18 13.5 8.5 8.5 13.5 1 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 18 23 18 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										{{ Math.abs(statistics.logsTrend || 0) }}%
									</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card shadow="hover" class="overview-card">
							<div class="overview-content">
								<div class="overview-icon success">
									<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										<circle cx="12" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
									</svg>
								</div>
								<div class="overview-info">
									<div class="overview-value">{{ statistics.activeUsers || 0 }}</div>
									<div class="overview-label">活跃用户数</div>
									<div class="overview-trend" :class="{ positive: statistics.usersTrend > 0, negative: statistics.usersTrend < 0 }">
										<svg v-if="statistics.usersTrend > 0" class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 6 13.5 15.5 8.5 10.5 1 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 6 23 6 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										<svg v-else class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 18 13.5 8.5 8.5 13.5 1 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 18 23 18 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										{{ Math.abs(statistics.usersTrend || 0) }}%
									</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card shadow="hover" class="overview-card">
							<div class="overview-content">
								<div class="overview-icon warning">
									<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<circle cx="12" cy="12" r="10"></circle>
										<line x1="12" y1="8" x2="12" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										<line x1="12" y1="16" x2="12.01" y2="16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
									</svg>
								</div>
								<div class="overview-info">
									<div class="overview-value">{{ statistics.abnormalOperations || 0 }}</div>
									<div class="overview-label">异常操作</div>
									<div class="overview-trend" :class="{ positive: statistics.abnormalTrend > 0, negative: statistics.abnormalTrend < 0 }">
										<svg v-if="statistics.abnormalTrend > 0" class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 6 13.5 15.5 8.5 10.5 1 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 6 23 6 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										<svg v-else class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 18 13.5 8.5 8.5 13.5 1 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 18 23 18 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										{{ Math.abs(statistics.abnormalTrend || 0) }}%
									</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card shadow="hover" class="overview-card">
							<div class="overview-content">
								<div class="overview-icon info">
									<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<circle cx="12" cy="12" r="10"></circle>
										<polyline points="12 6 12 12 16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
									</svg>
								</div>
								<div class="overview-info">
									<div class="overview-value">{{ statistics.avgResponseTime || 0 }}ms</div>
									<div class="overview-label">平均响应时间</div>
									<div class="overview-trend" :class="{ positive: statistics.responseTrend < 0, negative: statistics.responseTrend > 0 }">
										<svg v-if="statistics.responseTrend < 0" class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 6 13.5 15.5 8.5 10.5 1 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 6 23 6 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										<svg v-else class="trend-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<polyline points="23 18 13.5 8.5 8.5 13.5 1 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											<polyline points="17 18 23 18 23 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
										{{ Math.abs(statistics.responseTrend || 0) }}%
									</div>
								</div>
							</div>
						</el-card>
					</el-col>
				</el-row>
			</div>

			<!-- 图表区域 -->
			<div class="charts-container">
				<el-row :gutter="20">
					<!-- 操作类型统计 -->
					<el-col :span="12">
						<el-card shadow="hover" class="chart-card">
							<div class="chart-header">
								<h3>操作类型分布</h3>
								<el-button-group>
									<el-button :type="operationChartType === 'pie' ? 'primary' : ''" @click="operationChartType = 'pie'">饼图</el-button>
									<el-button :type="operationChartType === 'bar' ? 'primary' : ''" @click="operationChartType = 'bar'">柱状图</el-button>
								</el-button-group>
							</div>
							<div class="chart-content" ref="operationChart"></div>
						</el-card>
					</el-col>

					<!-- 用户活跃度统计 -->
					<el-col :span="12">
						<el-card shadow="hover" class="chart-card">
							<div class="chart-header">
								<h3>用户活跃度排行</h3>
								<el-button @click="loadUserActivity">
									<svg class="btn-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<polyline points="23 4 23 10 17 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
									</svg>
									刷新
								</el-button>
							</div>
							<div class="chart-content" ref="userActivityChart"></div>
						</el-card>
					</el-col>
				</el-row>

				<el-row :gutter="20" style="margin-top: 20px;">
					<!-- 时间趋势分析 -->
					<el-col :span="24">
						<el-card shadow="hover" class="chart-card">
							<div class="chart-header">
								<h3>操作时间趋势分析</h3>
								<el-radio-group v-model="trendInterval" @change="loadTimeTrend">
									<el-radio-button label="hour">按小时</el-radio-button>
									<el-radio-button label="day">按天</el-radio-button>
									<el-radio-button label="week">按周</el-radio-button>
									<el-radio-button label="month">按月</el-radio-button>
								</el-radio-group>
							</div>
							<div class="chart-content" ref="timeTrendChart"></div>
						</el-card>
					</el-col>
				</el-row>
			</div>

			<!-- 异常操作检测 -->
			<div class="abnormal-operations">
				<el-card shadow="hover">
					<div class="card-header">
						<h3>异常操作检测</h3>
						<el-button type="primary" @click="handleDetectAbnormalOperations">
							<svg class="btn-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
								<circle cx="11" cy="11" r="8"></circle>
								<path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
							</svg>
							检测异常
						</el-button>
					</div>
					<div class="abnormal-list">
						<el-table :data="abnormalOperations" v-loading="abnormalLoading" stripe>
							<el-table-column prop="username" label="用户名" width="120" align="center"></el-table-column>
							<el-table-column prop="operationType" label="操作类型" width="120" align="center">
								<template #default="scope">
									<el-tag :type="getOperationTypeTagType(scope.row.operationType)" size="small">
										{{ getOperationTypeLabel(scope.row.operationType) }}
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="description" label="异常描述" min-width="200"></el-table-column>
							<el-table-column prop="ip" label="IP地址" width="130" align="center"></el-table-column>
							<el-table-column prop="riskLevel" label="风险等级" width="100" align="center">
								<template #default="scope">
									<el-tag :type="getRiskLevelType(scope.row.riskLevel)" size="small">
										{{ scope.row.riskLevel }}
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="createdAt" label="操作时间" width="180" align="center">
								<template #default="scope">
									{{ formatDateTime(scope.row.createdAt) }}
								</template>
							</el-table-column>
							<el-table-column label="操作" width="120" align="center">
								<template #default="scope">
									<el-button type="text" @click="handleViewAbnormalDetail(scope.row)">查看详情</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-card>
			</div>
		</main>
	</div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
	getOperationLogStatistics,
	getOperationTypeStatistics,
	getUserActivityStatistics,
	getTimeTrendStatistics,
	detectAbnormalOperations
} from '@/api/operationLog'

export default {
	name: 'OperationLogStatistics',
	setup() {
		// 响应式数据
		const currentUser = ref(null)
		const abnormalLoading = ref(false)

		// 时间范围
		const timeRange = ref('week')
		const customDateRange = ref(null)

		// 统计数据
		const statistics = reactive({
			totalLogs: 0,
			activeUsers: 0,
			abnormalOperations: 0,
			avgResponseTime: 0,
			logsTrend: 0,
			usersTrend: 0,
			abnormalTrend: 0,
			responseTrend: 0
		})

		// 图表类型
		const operationChartType = ref('pie')
		const trendInterval = ref('day')

		// 异常操作
		const abnormalOperations = ref([])

		// 图表引用
		const operationChart = ref(null)
		const userActivityChart = ref(null)
		const timeTrendChart = ref(null)

		// 图表实例
		let operationChartInstance = null
		let userActivityChartInstance = null
		let timeTrendChartInstance = null

		// 操作类型选项
		const operationTypes = ref([
			{ label: '用户登录', value: 'LOGIN' },
			{ label: '用户登出', value: 'LOGOUT' },
			{ label: '新增', value: 'CREATE' },
			{ label: '修改', value: 'UPDATE' },
			{ label: '删除', value: 'DELETE' },
			{ label: '查询', value: 'QUERY' },
			{ label: '导入', value: 'IMPORT' },
			{ label: '导出', value: 'EXPORT' },
			{ label: '文件上传', value: 'UPLOAD' },
			{ label: '文件下载', value: 'DOWNLOAD' }
		])

		// 生命周期钩子
		onMounted(() => {
			// 获取当前用户信息
			currentUser.value = JSON.parse(localStorage.getItem('user')) || {}
			// 加载统计数据
			loadStatistics()
			loadOperationTypeStatistics()
			loadUserActivity()
			loadTimeTrend()
			// 初始化图表
			nextTick(() => {
				initCharts()
			})
		})

		onUnmounted(() => {
			// 销毁图表实例
			if (operationChartInstance) {
				operationChartInstance.dispose()
			}
			if (userActivityChartInstance) {
				userActivityChartInstance.dispose()
			}
			if (timeTrendChartInstance) {
				timeTrendChartInstance.dispose()
			}
		})

		// 加载统计数据
		const loadStatistics = async () => {
			try {
				const response = await getOperationLogStatistics(getTimeRangeParams())
				if (response.code === 200) {
					Object.assign(statistics, response.data)
				}
			} catch (error) {
				console.error('加载统计数据失败:', error)
			}
		}

		// 加载操作类型统计
		const loadOperationTypeStatistics = async () => {
			try {
				const response = await getOperationTypeStatistics(getTimeRange())
				if (response.code === 200) {
					updateOperationChart(response.data)
				}
			} catch (error) {
				console.error('加载操作类型统计失败:', error)
			}
		}

		// 加载用户活跃度统计
		const loadUserActivity = async () => {
			try {
				const response = await getUserActivityStatistics(getTimeRange())
				if (response.code === 200) {
					updateUserActivityChart(response.data)
				}
			} catch (error) {
				console.error('加载用户活跃度统计失败:', error)
			}
		}

		// 加载时间趋势统计
		const loadTimeTrend = async () => {
			try {
				const response = await getTimeTrendStatistics(getTimeRange())
				if (response.code === 200) {
					updateTimeTrendChart(response.data)
				}
			} catch (error) {
				console.error('加载时间趋势统计失败:', error)
			}
		}

		// 检测异常操作
		const handleDetectAbnormalOperations = async () => {
			abnormalLoading.value = true
			try {
				const response = await detectAbnormalOperations(getTimeRangeParams())
				if (response.code === 200) {
					abnormalOperations.value = response.data
					ElMessage.success(`检测到${response.data.length}条异常操作`)
				} else {
					ElMessage.error(response.message || '检测失败')
				}
			} catch (error) {
				console.error('检测异常操作失败:', error)
				ElMessage.error('检测失败')
			} finally {
				abnormalLoading.value = false
			}
		}

		// 初始化图表
		const initCharts = () => {
			// 操作类型统计图表
			operationChartInstance = echarts.init(operationChart.value)

			// 用户活跃度图表
			userActivityChartInstance = echarts.init(userActivityChart.value)

			// 时间趋势图表
			timeTrendChartInstance = echarts.init(timeTrendChart.value)

			// 监听窗口大小变化
			window.addEventListener('resize', handleResize)
		}

		// 更新操作类型图表
		const updateOperationChart = (data) => {
			if (!operationChartInstance) return

			const option = operationChartType.value === 'pie' ? {
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b}: {c} ({d}%)'
				},
				legend: {
					orient: 'vertical',
					left: 10,
					data: data.map(item => item.name)
				},
				series: [{
					name: '操作类型',
					type: 'pie',
					radius: ['50%', '70%'],
					avoidLabelOverlap: false,
					label: {
						show: false,
						position: 'center'
					},
					emphasis: {
						label: {
							show: true,
							fontSize: '18',
							fontWeight: 'bold'
						}
					},
					labelLine: {
						show: false
					},
					data: data
				}]
			} : {
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'shadow'
					}
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis: {
					type: 'category',
					data: data.map(item => item.name),
					axisLabel: {
						interval: 0,
						rotate: 45
					}
				},
				yAxis: {
					type: 'value'
				},
				series: [{
					name: '操作次数',
					type: 'bar',
					data: data,
					itemStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
							{ offset: 0, color: '#83bff6' },
							{ offset: 0.5, color: '#188df0' },
							{ offset: 1, color: '#188df0' }
						])
					}
				}]
			}

			operationChartInstance.setOption(option)
		}

		// 更新用户活跃度图表
		const updateUserActivityChart = (data) => {
			if (!userActivityChartInstance) return

			const option = {
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'shadow'
					}
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis: {
					type: 'value'
				},
				yAxis: {
					type: 'category',
					data: data.map(item => item.username).reverse()
				},
				series: [{
					name: '操作次数',
					type: 'bar',
					data: data.map(item => item.count).reverse(),
					itemStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
							{ offset: 0, color: '#37a2da' },
							{ offset: 1, color: '#32c5e9' }
						])
					}
				}]
			}

			userActivityChartInstance.setOption(option)
		}

		// 更新时间趋势图表
		const updateTimeTrendChart = (data) => {
			if (!timeTrendChartInstance) return

			const option = {
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data: ['操作次数', '活跃用户']
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: data.map(item => item.time)
				},
				yAxis: {
					type: 'value'
				},
				series: [
					{
						name: '操作次数',
						type: 'line',
						smooth: true,
						data: data.map(item => item.operationCount),
						itemStyle: {
							color: '#5470c6'
						},
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
								{ offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
							])
						}
					},
					{
						name: '活跃用户',
						type: 'line',
						smooth: true,
						data: data.map(item => item.activeUsers),
						itemStyle: {
							color: '#91cc75'
						},
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: 'rgba(145, 204, 117, 0.3)' },
								{ offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
							])
						}
					}
				]
			}

			timeTrendChartInstance.setOption(option)
		}

		// 处理窗口大小变化
		const handleResize = () => {
			if (operationChartInstance) {
				operationChartInstance.resize()
			}
			if (userActivityChartInstance) {
				userActivityChartInstance.resize()
			}
			if (timeTrendChartInstance) {
				timeTrendChartInstance.resize()
			}
		}

		// 时间范围改变
		const handleTimeRangeChange = () => {
			customDateRange.value = null
			refreshAllData()
		}

		// 自定义日期范围改变
		const handleCustomDateChange = () => {
			if (customDateRange.value) {
				timeRange.value = ''
				refreshAllData()
			}
		}

		// 刷新所有数据
		const refreshAllData = () => {
			loadStatistics()
			loadOperationTypeStatistics()
			loadUserActivity()
			loadTimeTrend()
		}

		// 获取时间范围参数
		const getTimeRangeParams = () => {
			if (customDateRange.value && customDateRange.value.length === 2) {
				return {
					startTime: customDateRange.value[0],
					endTime: customDateRange.value[1]
				}
			}
			return { timeRange: getTimeRange() }
		}

		// 获取时间范围
		const getTimeRange = () => {
			return timeRange.value || 'custom'
		}

		// 查看异常详情
		const handleViewAbnormalDetail = (row) => {
			// 这里可以打开详情对话框或跳转到详情页面
			ElMessage.info(`查看用户 ${row.username} 的异常操作详情`)
		}

		// 获取操作类型标签类型
		const getOperationTypeTagType = (operationType) => {
			const typeMap = {
				'LOGIN': 'success',
				'LOGOUT': 'info',
				'CREATE': 'primary',
				'UPDATE': 'warning',
				'DELETE': 'danger',
				'QUERY': '',
				'IMPORT': 'success',
				'EXPORT': 'primary',
				'UPLOAD': 'warning',
				'DOWNLOAD': 'info'
			}
			return typeMap[operationType] || ''
		}

		// 获取操作类型标签
		const getOperationTypeLabel = (operationType) => {
			const type = operationTypes.value.find(t => t.value === operationType)
			return type ? type.label : operationType
		}

		// 获取风险等级类型
		const getRiskLevelType = (riskLevel) => {
			const typeMap = {
				'低': 'success',
				'中': 'warning',
				'高': 'danger'
			}
			return typeMap[riskLevel] || 'info'
		}

		// 格式化日期时间
		const formatDateTime = (dateTime) => {
			if (!dateTime) return '-'
			return new Date(dateTime).toLocaleString('zh-CN')
		}

		// 退出登录
		const handleLogout = () => {
			ElMessageBox.confirm('确定要退出登录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				// 清除用户信息
				localStorage.removeItem('user')
				localStorage.removeItem('token')
				// 跳转到登录页
				window.location.href = '/login'
			})
		}

		// 监听图表类型变化
		watch(operationChartType, () => {
			loadOperationTypeStatistics()
		})

		// 返回所有需要暴露的响应式数据和方法
		return {
			// 响应式数据
			currentUser,
			abnormalLoading,
			timeRange,
			customDateRange,
			statistics,
			operationChartType,
			trendInterval,
			abnormalOperations,
			operationChart,
			userActivityChart,
			timeTrendChart,
			operationTypes,

			// 方法
			loadStatistics,
			loadOperationTypeStatistics,
			loadUserActivity,
			loadTimeTrend,
			handleDetectAbnormalOperations,
			handleTimeRangeChange,
			handleCustomDateChange,
			handleViewAbnormalDetail,
			handleLogout,
			getOperationTypeTagType,
			getOperationTypeLabel,
			getRiskLevelType,
			formatDateTime
		}
	}
}
</script>

<style scoped>
/* 基础样式 */
* {
	font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
	background-color: #f0f2f5;
	color: #1a1a1a;
	margin: 0;
}

/* 容器布局 */
.app-container {
	max-width: 1440px;
	margin: 0 auto;
	display: grid;
	grid-template-columns: 240px 1fr;
	grid-template-rows: 64px 1fr;
	min-height: 100vh;
	background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
	grid-column: 1 / -1;
	background-color: #2C5AA0;
	display: flex;
	align-items: center;
	padding: 0 24px;
}

.logo {
	font-size: 18px;
	font-weight: bold;
	color: white;
	display: flex;
	align-items: center;
	gap: 8px;
}

.flex-grow {
	flex-grow: 1;
}

.flex {
	display: flex;
}

.items-center {
	align-items: center;
}

.gap-6 {
	gap: 24px;
}

.gap-2 {
	gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
	background-color: white;
	padding: 16px 0;
	border-right: 1px solid #e4e7ed;
}

.menu-item {
	padding: 12px 24px;
	color: #555;
	display: flex;
	align-items: center;
	gap: 12px;
	transition: all 0.3s;
	cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
	background-color: #e8eff9;
	color: #2C5AA0;
	border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
	padding: 24px;
	display: grid;
	grid-template-rows: auto 1fr;
	gap: 24px;
	overflow-y: auto;
}

.main-content-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 16px;
	border-bottom: 1px solid #e4e7ed;
}

.header-actions {
	display: flex;
	gap: 12px;
}

/* 时间范围选择器 */
.time-range-selector {
	margin-bottom: 24px;
}

.time-range-content {
	display: flex;
	align-items: center;
	gap: 16px;
}

.time-label {
	font-weight: 500;
	color: #606266;
}

/* 概览卡片 */
.overview-cards {
	margin-bottom: 24px;
}

.overview-card {
	height: 120px;
}

.overview-content {
	display: flex;
	align-items: center;
	height: 100%;
	gap: 16px;
}

.overview-icon {
	width: 70px;
	height: 70px;
	border-radius: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28px;
	color: white;
}

.overview-icon.primary {
	background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.overview-icon.success {
	background: linear-gradient(135deg, #67C23A, #85CE61);
}

.overview-icon.warning {
	background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.overview-icon.info {
	background: linear-gradient(135deg, #909399, #A6A9AD);
}

.overview-info {
	flex: 1;
}

.overview-value {
	font-size: 28px;
	font-weight: bold;
	color: #303133;
	line-height: 1;
}

.overview-label {
	font-size: 14px;
	color: #909399;
	margin-top: 4px;
}

.overview-trend {
	font-size: 12px;
	margin-top: 4px;
	display: flex;
	align-items: center;
	gap: 4px;
}

.overview-trend.positive {
	color: #67C23A;
}

.overview-trend.negative {
	color: #F56C6C;
}

/* 图表容器 */
.charts-container {
	margin-bottom: 24px;
}

.chart-card {
	height: 400px;
}

.chart-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.chart-header h3 {
	margin: 0;
	color: #303133;
}

.chart-content {
	height: 320px;
}

/* 异常操作检测 */
.abnormal-operations {
	margin-bottom: 24px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.card-header h3 {
	margin: 0;
	color: #303133;
}

.abnormal-list {
	max-height: 400px;
	overflow-y: auto;
}

/* 头像和退出登录 */
#img-head {
	height: 40px;
	width: 40px;
	border-radius: 50px;
}

.denglu {
	color: white;
	font-size: 15px;
	text-decoration: none;
}

.denglu:hover {
	color: #F44346;
}

.text-sm {
	font-size: 14px;
}

.text-white {
	color: white;
}

/* 图标样式 */
.logo-icon {
	width: 28px;
	height: 28px;
	color: white;
	transition: transform 0.3s ease;
}

.logo:hover .logo-icon {
	transform: rotate(360deg);
}

.logout-icon {
	width: 18px;
	height: 18px;
	margin-right: 6px;
	vertical-align: middle;
	transition: transform 0.3s ease;
}

.logout-icon:hover {
	transform: translateX(2px);
}

.menu-icon {
	width: 18px;
	height: 18px;
	transition: transform 0.3s ease;
}

.menu-item:hover .menu-icon {
	transform: scale(1.1);
}

.btn-icon {
	width: 16px;
	height: 16px;
	margin-right: 6px;
	vertical-align: middle;
	transition: transform 0.3s ease;
}

:hover .btn-icon {
	transform: scale(1.1);
}

.trend-icon {
	width: 14px;
	height: 14px;
	animation: trendPulse 2s infinite;
}

@keyframes trendPulse {
	0%, 100% { opacity: 1; }
	50% { opacity: 0.7; }
}

/* Element UI 样式调整 */
.el-table {
	margin-top: 16px;
	border-radius: 8px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
	background-color: #fafafa !important;
	color: #606266;
	font-weight: 600;
}

.el-table td {
	padding: 12px 0;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
	background-color: #f8f9fa;
}

.el-card {
	border: none;
	border-radius: 12px;
	overflow: hidden;
	transition: all 0.3s ease;
}

.el-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.el-button {
	border-radius: 8px;
	transition: all 0.3s ease;
}

.el-button:hover {
	transform: translateY(-1px);
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-radio-group .el-radio-button__inner {
	border-radius: 8px;
	transition: all 0.3s ease;
}

.el-date-picker {
	border-radius: 8px;
}

.el-tag {
	border-radius: 6px;
	font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
	.overview-cards .el-col {
		margin-bottom: 16px;
	}

	.charts-container .el-col {
		margin-bottom: 20px;
	}
}

@media (max-width: 768px) {
	.app-container {
		grid-template-columns: 1fr;
	}

	.sidebar {
		display: none;
	}

	.header {
		padding: 0 16px;
	}

	.content {
		padding: 16px;
	}

	.time-range-content {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
	}

	.overview-content {
		flex-direction: column;
		text-align: center;
		gap: 12px;
	}

	.overview-icon {
		width: 50px;
		height: 50px;
		font-size: 20px;
	}

	.overview-value {
		font-size: 24px;
	}

	.chart-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
	}

	.chart-content {
		height: 280px;
	}
}
</style>